package com.wngbms.guava;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

@Slf4j
public class SemaphoneTest {

    public static void main(String[] args) throws InterruptedException {
        Semaphore semaphore = new Semaphore(3);

        CountDownLatch countDownLatch = new CountDownLatch(10);

        Runnable runnable = () -> {
            try {
                semaphore.acquire(2);
                log.info("start");
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                semaphore.release(2);
            }
            log.info("end");
            countDownLatch.countDown();
        };

        ExecutorService executorService = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 10; i++) {
            executorService.submit(runnable);
        }

        countDownLatch.await();
        executorService.shutdown();
    }
}
